using System;
using System.Collections.Generic;
using Agatha.Common;
using Source.Common;


namespace  Source.Web.FrameWork
{
    public class ErrorHelper
    {
        private readonly IViewPart view;

        public ErrorHelper(IViewPart view)
        {
            this.view = view;
        }

        public bool HandlePossibleErrors(Response response)
        {
            return HandlePossibleErrors(response, false);
        }

        public bool HandlePossibleErrors(Response response, bool rethrowException)
        {
            if (response.Exception != null)
            {
                if (rethrowException)
                {
                    throw new Exception(response.Exception.Message);
                }

                view.DisplayMessages(response.Exception.Message);
                return true;
            }

            return false;
        }

        public bool HandlePossibleErrors(IEnumerable<Response> responses)
        {
            return HandlePossibleErrors(responses, false);
        }

        public bool HandlePossibleErrors(IEnumerable<Response> responses, bool rethrowFirstEncounteredException)
        {
            bool errorsOccured = false;

            foreach (Response response in responses)
            {
                errorsOccured = errorsOccured || HandlePossibleErrors(response, rethrowFirstEncounteredException);
            }

            return errorsOccured;
        }

        public bool HandlePossibleValidationMessages(ResponseWithValidationSummary response)
        {
            if (response.ValidationSummary.HasMessages)
            {
                view.DisplayMessages(response.ValidationSummary.GetMessages());
            }

            return response.ValidationSummary.HasMessages;
        }
    }
}